<template>
  <div class="gl_contentBox gl_heightFull">
    <div class="demo-input-suffix gl_searchBox gl_mb_15">
      <el-row :gutter="20">
        <el-col :span="4">
          <p>课程名称</p>
          <el-select v-model="qo.CourseName" size="mini" placeholder="请选择状态" filterable @change="getPageList()">
            <el-option v-for="(item, index) in courseList" :key="index" :value="item.name" :label="item._showName" />
          </el-select>
        </el-col>
        <el-col :span="4">
          <p>所属班级</p>
          <el-select v-model="qo.ClassName" size="mini" placeholder="请选择状态" filterable @change="getPageList()">
            <el-option v-for="(item, index) in classList" :key="index" :value="item.name" :label="item._showName" />
          </el-select>
        </el-col>
        <el-col :span="6">
          <p>上课日期</p>
          <el-time-picker
            v-model="qoTime"
            is-range
            format="HH:mm"
            value-format="HH:mm"
            :picker-options="{ selectableRange:DisApplyTimeHours }"
            size="mini"
            style="width: 100%"
            range-separator="至"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
            @change="changeAttendance"
          />
          <!-- <el-date-picker
            v-model="qoDate"
            size="mini"
            style="width: 100%"
            type="daterange"
            range-separator="至"
            start-placeholder="上课开始日期"
            end-placeholder="上课结束日期"
            value-format="yyyy-MM-dd"
            @change="changeAttendance"
          /> -->
        </el-col>
        <el-col :span="4">
          <p>学员姓名</p>
          <el-input v-model="qo.StudentName" placeholder="请输入学员姓名" size="mini" clearable @change="getPageList()" />
        </el-col>
        <el-col :span="6" class="search_btn">
          <div class="gl_clear">
            <div class="gl_fl">
              <el-button type="primary" size="mini" @click="getPageList()">筛选</el-button>
              <el-button type="warning" size="mini" @click="reset()">重置</el-button>
            </div>
            <div class="gl_fr">
              <el-button type="primary" size="mini" :loading="downloadLoading" @click="exportFile()">导出数据</el-button>
            </div>
          </div>
        </el-col>
      </el-row>
    </div>
    <div class="gl_mb_15 quick_date">
      <!-- <span class="gl_mr_10">上课时间：</span> -->
      <el-radio-group v-model="currentQuickDate" class="gl_mr_10" size="small" @change="changeQuickDate">
        <el-radio-button v-for="item in quickDateList" :key="item.code" :label="item.code">
          {{ item.name }}
        </el-radio-button>
      </el-radio-group>
    </div>

    <el-table v-loading="tableLoading" class="gl_table_noBorder gl_mb_15" :data="tableData" size="mini">
      <el-table-column type="index" label="序号" />
      <el-table-column prop="studentName" label="学员" />
      <el-table-column prop="coureName" label="课程名称" />
      <el-table-column prop="className" label="所属班级" />
      <el-table-column prop="coachName" label="教练" />
      <el-table-column width="200" prop="name" label="上课时间">
        <template slot-scope="{row}">
          <span class="gl_mr_5">{{ row.courseDate ? row.courseDate.slice(0, 10) : '' }}</span>
          <span>{{ row.startHour > 9 ? row.startHour : '0' + row.startHour }}:{{ row.startMinute > 9 ? row.startMinute : '0' + row.startMinute }}</span>
          <span> - </span>
          <span>{{ row.endHour > 9 ? row.endHour : '0' + row.endHour }}:{{ row.endMinute > 9 ? row.endMinute : '0' + row.endMinute }}</span>
        </template>
      </el-table-column>
      <el-table-column label="签到时间">
        <template slot-scope="{row}">
          <span class="gl_mr_5">{{ row.checkInTime ? row.checkInTime.slice(0, 10) : '' }}</span>
          <span>{{ row.checkInTime ? row.checkInTime.slice(11, 16) : '' }}</span>
        </template>
      </el-table-column>
      <el-table-column label="签退时间">
        <template slot-scope="{row}">
          <span class="gl_mr_5">{{ row.checkOutTime ? row.checkOutTime.slice(0, 10) : '' }}</span>
          <span>{{ row.checkOutTime ? row.checkOutTime.slice(11, 16) : '' }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="checkInStatusCode" label="到课状态">
        <template slot-scope="{row}">
          <span v-if="row.checkInStatusCode === 'Present'">到课</span>
          <span v-if="row.checkInStatusCode === 'NonePresent'">未到课</span>
        </template>
      </el-table-column>
      <el-table-column prop="deductClassPeriod" label="消耗课时" align="center" />
      <el-table-column label="操作" width="180">
        <template slot-scope="{ row }">
          <el-button size="mini" type="text" :disabled="Boolean(row.checkOutTime)" @click="clickSignOut(row)">签退</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <el-row style="text-align: right;">
      <el-pagination
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        :page-sizes="[10, 20, 30, 40]"
        :page-size="qo.MaxResultCount"
        :current-page="qo.Page"
        @size-change="changePageSize"
        @current-change="changePage"
      />
    </el-row>
  </div>
</template>

<script>
import {
  api_GET_ClubClass, // 获取班级列表
  api_GET_ClubCourse, // 获取课程列表
  api_GET_ClubCheckInLog, // 获取学员签到列表
  api_POST_ClubCheckInLogIdCheckOut // 签到
} from '@/extend/api/hallswaggerApi/app.js';

import {
  Api_GET_ClubCheckInLogQO
} from '@/lib/form/hall/swaggerForm.js';

import { api_GET_DownLoadFileAddHeader } from '@/extend/api/file';
import { errorText } from '@/lib';

export default {
  data () {
    return {
      quickDateList: [
        {
          code: 'Yesterday',
          name: '昨天'
        },
        {
          code: 'Today',
          name: '今天'
        },
        {
          code: 'Tomorrow',
          name: '明天'
        },
        {
          code: 'Week',
          name: '本周'
        },
        {
          code: 'Month',
          name: '本月'
        },
        {
          code: null,
          name: '全部'
        }
      ],
      qo: new Api_GET_ClubCheckInLogQO(),
      currentQuickDate: '',
      qoDate: [],
      DisApplyTimeHours: '00:00 - 23:59', // 可选时间段  ！！注意中间空格
      qoTime: [new Date(2016, 9, 10, 0, 0), new Date(2016, 9, 10, 23, 59)],
      tableLoading: false,
      tableData: [],
      total: 0,
      classList: [],
      courseList: [],
      downloadLoading: false
    };
  },
  computed: {
    quickDateObj () {
      const _today = new Date();
      const _returnResult = {};
      for (let i = 0; i < this.quickDateList.length; i++) {
        const item = this.quickDateList[i];
        _returnResult[item.code] = this.computeDateTime(item.code, _today);
      }
      return _returnResult;
    }
  },
  created () {
    this.getClass();
    this.getCourse();
    this.getTodayPageList();
  },
  methods: {
    // 计算时间
    computeDateTime(code, date) {
      const _dayTime = 86400000; // 一天的时间戳
      const _today = this.getDateData(date);
      if (code === 'Today') {
        // 今天
        return {
          StartDateTime: `${_today.year}-${_today.monthStr}-${_today.dateStr}`,
          EndDateTime: `${_today.year}-${_today.monthStr}-${_today.dateStr}`
        };
      } else if (code === 'Yesterday') {
        // 昨天
        const _yesterdayTime = _today.time - _dayTime;
        const _yesterday = new Date(_yesterdayTime);
        const _yesterdayFormat = this.getDateData(_yesterday);
        return {
          StartDateTime: `${_yesterdayFormat.year}-${_yesterdayFormat.monthStr}-${_yesterdayFormat.dateStr}`,
          EndDateTime: `${_yesterdayFormat.year}-${_yesterdayFormat.monthStr}-${_yesterdayFormat.dateStr}`
        };
      } else if (code === 'Tomorrow') {
        // 明天
        const _yesterdayTime = _today.time + _dayTime;
        const _yesterday = new Date(_yesterdayTime);
        const _yesterdayFormat = this.getDateData(_yesterday);
        return {
          StartDateTime: `${_yesterdayFormat.year}-${_yesterdayFormat.monthStr}-${_yesterdayFormat.dateStr}`,
          EndDateTime: `${_yesterdayFormat.year}-${_yesterdayFormat.monthStr}-${_yesterdayFormat.dateStr}`
        };
      } else if (code === 'Week') {
        // 本周
        const _weekStartDateTime = _today.time - ((_today.day - 1) * _dayTime);
        const _weekStartDate = new Date(_weekStartDateTime);
        const _weekStartDateFormat = this.getDateData(_weekStartDate);
        const _weekEndDateTime = _today.time + ((7 - _today.day) * _dayTime);
        const _weekEndDate = new Date(_weekEndDateTime);
        const _weekEndDateFormat = this.getDateData(_weekEndDate);
        return {
          StartDateTime: `${_weekStartDateFormat.year}-${_weekStartDateFormat.monthStr}-${_weekStartDateFormat.dateStr}`,
          EndDateTime: `${_weekEndDateFormat.year}-${_weekEndDateFormat.monthStr}-${_weekEndDateFormat.dateStr}`
        };
      } else if (code === 'Month') {
        // 本月
        const _monthStartDateTime = _today.time - ((_today.date - 1) * _dayTime);
        const _monthStartDate = new Date(_monthStartDateTime);
        const _monthStartDateFormat = this.getDateData(_monthStartDate);
        const _monthLastDay = new Date(_today.year, _today.month, 0); // 本月最后一天
        const _monthEndDateFormat = this.getDateData(_monthLastDay);
        return {
          StartDateTime: `${_monthStartDateFormat.year}-${_monthStartDateFormat.monthStr}-${_monthStartDateFormat.dateStr}`,
          EndDateTime: `${_monthEndDateFormat.year}-${_monthEndDateFormat.monthStr}-${_monthEndDateFormat.dateStr}`
        };
      } else {
        // 其他情况
        return {
          StartDateTime: null,
          EndDateTime: null
        };
      }
    },
    // 导出数据
    exportFile () {
      this.downloadLoading = true;
      const tempUrl = `/api/excel`;
      const fileName = '签退' + '.xlsx';
      const _qo = JSON.parse(JSON.stringify(this.qo));
      delete _qo.MaxResultCount;
      delete _qo.Page;
      delete _qo.SkipCount;
      api_GET_DownLoadFileAddHeader(
        tempUrl,
        fileName,
        {
          ReportName: 'CheckInList',
          GetCheckInLogInput: JSON.stringify(_qo)
        },
        WEB_CONFIG.VUE_APP_SWAGGER_HALL_BASE
      )
        .then(
          res => {
            this.downloadLoading = false;
          }
        )
        .catch(
          error => {
            this.downloadLoading = false;
            errorText(error)
              .then(
                (text) => {
                  this.$message({ type: 'error', message: text });
                }
              );
          }
        );
    },
    // 获取班级列表
    getClass () {
      api_GET_ClubClass()
        .then(
          res => {
            const _list = res.items || [];
            _list.forEach(item => {
              item._showName = item.name;
            });
            _list.unshift({
              name: '',
              _showName: '全部'
            });
            this.classList = _list;
          }
        );
    },
    // 获取课程列表
    getCourse () {
      api_GET_ClubCourse()
        .then(
          res => {
            const _list = res.items || [];
            _list.forEach(item => {
              item._showName = item.name;
            });
            _list.unshift({
              name: '',
              _showName: '全部'
            });
            this.courseList = _list;
          }
        );
    },
    // 第一次获取今日数据
    getTodayPageList () {
      this.qo.Page = 1;
      this.qo.SkipCount = (this.qo.Page - 1) * this.qo.MaxResultCount;
      this.qo.CheckInOut = false;
      this.qo.CheckInTime = true;
      this.qo.StartDateTime = this.quickDateObj.Today.StartDateTime;
      this.qo.EndDateTime = this.quickDateObj.Today.EndDateTime;
      this.qoDate = [this.qo.StartDateTime, this.qo.EndDateTime];
      this.qo.StartHour = '00';
      this.qo.StartMinute = '00';
      this.qo.EndHour = '23';
      this.qo.EndMinute = '59';
      this.currentQuickDate = 'Today';
      this.qo.Sorting = 'CourseDate,StartHour,StartMinute ASC';
      this.apiGetClubCheckInLog(this.qo);
    },
    // 获取列表
    getPageList(page) {
      this.qo.Page = page || 1;
      this.qo.SkipCount = (this.qo.Page - 1) * this.qo.MaxResultCount;
      this.qo.CheckInOut = false;
      this.qo.CheckInTime = true;
      this.qo.Sorting = 'CourseDate,StartHour,StartMinute ASC';
      this.apiGetClubCheckInLog(this.qo);
    },
    // 获取签到列表API
    apiGetClubCheckInLog (qo) {
      // 后端要求传值，否则无法查询最后一天
      if (this.qo.EndDateTime) {
        this.qo.EndDateTime = this.qo.EndDateTime.length === 10 ? this.qo.EndDateTime + ' 23:59:59' : this.qo.EndDateTime;
      }
      this.tableLoading = true;
      api_GET_ClubCheckInLog(qo)
        .then(
          res => {
            this.tableLoading = false;
            this.total = res.totalCount;
            this.tableData = res.items || [];
            console.log('res: ', res);
          }
        )
        .catch(
          error => {
            this.tableLoading = false;
            this.$message({
              message: `获取失败 ${error.error.message}`,
              type: 'error',
              showClose: true
            });
          }
        );
    },
    // 重置QO
    reset () {
      this.currentQuickDate = 'Today';
      this.qo = new Api_GET_ClubCheckInLogQO();
      this.qo.StartDateTime = this.quickDateObj.Today.StartDateTime;
      this.qo.EndDateTime = this.quickDateObj.Today.EndDateTime;
      this.qoTime = [new Date(2016, 9, 10, 0, 0), new Date(2016, 9, 10, 23, 59)];
      this.qo.StartHour = '00';
      this.qo.StartMinute = '00';
      this.qo.EndHour = '23';
      this.qo.EndMinute = '59';
      this.qoDate = [];
      this.getPageList();
    },
    // 切换考勤日期
    changeAttendance (val) {
      const _start = val ? val[0] : null;
      const _end = val ? val[1] : null;
      this.qo.StartHour = _start ? _start.slice(0, 2) : null;
      this.qo.EndHour = _end ? _end.slice(0, 2) : null;
      this.qo.StartMinute = _start ? _start.slice(3, 5) : null;
      this.qo.EndMinute = _end ? _end.slice(3, 5) : null;
      // const _qucikDateCode = this.matchQuickDate(_start, _end);
      // this.currentQuickDate = _qucikDateCode;
      // this.qo.StartDateTime = _start;
      // this.qo.EndDateTime = _end;
      this.getPageList();
    },
    matchQuickDate (start, end) {
      for (const k in this.quickDateObj) {
        if (Object.hasOwnProperty.call(this.quickDateObj, k)) {
          const ktem = this.quickDateObj[k];
          if (start === ktem.StartDateTime && end === ktem.EndDateTime) {
            return k;
          }
        }
      }
      return 'custom';
    },
    // 点击表格内签到按钮
    clickSignOut (row) {
      if (row.checkLogId) {
        this.apiClubCheckInLogCheckIn(row.checkLogId);
      } else {
        this.$message({
          message: `签退失败，【${row.studentName}】还未签到，无法签退`,
          type: 'warning',
          showClose: true
        });
      }
    },
    // 签退接口
    apiClubCheckInLogCheckIn (checkLogId) {
      this.tableLoading = true;
      api_POST_ClubCheckInLogIdCheckOut(checkLogId)
        .then(
          res => {
            this.tableLoading = false;
            this.total = res.totalCount;
            this.tableData = res.items || [];
            this.getPageList(this.qo.Page);
            console.log('res: ', res);
            this.$message({
              message: `签退成功`,
              type: 'success',
              showClose: true
            });
          }
        )
        .catch(
          error => {
            this.tableLoading = false;
            this.$message({
              message: `签退失败 ${error.error.message}`,
              type: 'error',
              showClose: true
            });
          }
        );
    },
    // 快捷选择上课时间
    changeQuickDate (val) {
      const _date = this.quickDateObj[val];
      this.qo.StartDateTime = _date.StartDateTime;
      this.qo.EndDateTime = _date.EndDateTime;
      this.qoDate = val === null ? [] : [_date.StartDateTime, _date.EndDateTime];
      this.getPageList();
    },
    // 获取想要的时间数据
    getDateData (date) {
      const _year = date.getFullYear(); // 当前年
      const _month = date.getMonth() + 1; // 当前月
      const _date = date.getDate(); // 当前日
      const _day = date.getDay(); // 当前周几
      const _time = date.getTime(); // 当前时间戳
      const _strMonth = _month <= 9 ? '0' + _month : _month;
      const _strDate = _date <= 9 ? '0' + _date : _date;
      return {
        year: _year,
        month: _month,
        monthStr: _strMonth,
        date: _date,
        dateStr: _strDate,
        day: _day,
        time: _time
      };
    },
    // 分页
    changePage(page) {
      this.getPageList(page);
    },
    changePageSize(pagesize) {
      this.qo.MaxResultCount = pagesize;
      this.getPageList();
    }
  }
};
</script>

<style lang="scss" scoped>
  .quick_date {
    font-size: 12px;
    line-height: 32px;
  }
</style>
